package com.lymei.core.modules.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lymei.common.utils.RedisUtils;
import com.lymei.core.modules.system.service.IOnlineService;
import com.lymei.lib.properties.AppProperties;
import com.lymei.lib.vo.system.UserVo;
import com.sun.istack.NotNull;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author lymei
 * @title: OnlineServiceImpl
 * @projectName scui-admin
 * @description: TODO
 * @date 2022/1/2411:05
 */
@Service
public class OnlineServiceImpl implements IOnlineService {

    @Autowired
    private AppProperties appProperties;

    @Autowired
    private RedisUtils redisUtils;

    private final Long critical = 5*60L;

    @Override
    public void put(String token,UserVo user) {
        redisUtils.set(appProperties.getOnline().getOnlineKeyPrefix()+token,user,appProperties.getOnline().getTokenExpire(), TimeUnit.SECONDS);
    }

    @Override
    public void remove(String token) {
        redisUtils.del(appProperties.getOnline().getOnlineKeyPrefix()+token);
    }


    @Override
    public List<UserVo> online() {
        var keys = redisUtils.likeKeys(appProperties.getOnline().getTokenPrefix());
        List<UserVo> userVos = new ArrayList<>();
        for (String s : Optional.ofNullable(keys).orElse(new LinkedHashSet<>())) {
            userVos.add(this.get(s));
        }
        return userVos;
    }

    @Override
    public boolean has(String token) {
        return redisUtils.hasKey(appProperties.getOnline().getOnlineKeyPrefix()+token);
    }

    @Override
    public UserVo get(String token) {
        if (this.has(token)){
            return (UserVo) redisUtils.get(appProperties.getOnline().getOnlineKeyPrefix()+token);
        }
        return null;
    }

    @Override
    public UserVo get(HttpServletRequest request) {
        String token = request.getHeader(appProperties.getOnline().getTokenHeaderName());
        String prefix = appProperties.getOnline().getTokenPrefix();
        if (StringUtils.isBlank(token)){
            return null;
        }
        if (!token.contains(prefix)){
            return null;
        }
        token = token.replace(prefix,"");
        if (this.has(token)){
            long expireTime = redisUtils.getExpire(token);
            if (expireTime < critical){
                redisUtils.expire(token,appProperties.getOnline().getTokenExpire(),TimeUnit.SECONDS);
            }
            return this.get(token);
        }
        return null;
    }
}
